let express = require('express')
let router = express.Router()

let mysqlHelper = require('../utils/mysqlHelper.js')

// 创建
router.post('/', async function (req, res, next) {
    let result = {}
    try {
        let userData = await mysqlHelper.query("select * from sys_user where username='" + req.body.username + "' and password='" + req.body.password + "'")
        if (userData.length == 0) {
            throw new Error('用户名或密码错误。')
        }
        req.session.user = userData[0]
        sqlStr = "select distinct a.* "
        sqlStr += "from sys_permissions a "
        sqlStr += "inner join sys_role_permission b on a.id=b.permissionId "
        sqlStr += "inner join sys_user_role c on b.roleId=c.roleId "
        sqlStr += "where c.userId='" + userData[0].userId + "' and b.type=2 and b.permissionId is not null "
        sqlStr += "order by a.menuId,a.orderInList "
        let rows = await mysqlHelper.query(sqlStr)
        let permissions = {}
        rows.forEach((permission, index, arr) => {
            if (permissions[permission.menuId] == null) {
                permissions[permission.menuId] = []
            }
            permissions[permission.menuId].push(permission.name)
        })
        req.session.permissions = permissions

        result.success = true
    } catch (err) {
        result.success = false
        result.err = err.message
    }
    res.json(result)
})

// 获取
router.get('/', async function (req, res, next) {
    let result = {}
    try {
        result.user = req.session.user
        result.permissions = req.session.permissions
        result.success = true
    } catch (err) {
        result.success = false
        result.err = err.message
    }
    res.json(result)
})

// 删除
router.delete('/', async function (req, res, next) {
    let result = {}
    try {
        req.session.user = null
        req.session.permissions = null
        result.success = true
    } catch (err) {
        result.success = false
        result.err = err.message
    }
    res.json(result)
})

// 获取token
router.post('/token', async function (req, res, next) {
    let result = {}
    let userId = 0
    try {
        let rows = await mysqlHelper.query("select userId, userName,name from sys_user where userName='" + req.body.username + "' and password='" + req.body.password + "'")
        if (rows.length == 0) {
            throw new Error('用户名或密码错误。')
        }
        else{
            if (rows[0].status=='0')
                throw new Error('用户已停用。')
            userId = rows[0].userId
        }
        req.session.userInfo = rows[0]

        let user = {}
        user.userInfo = rows[0]
        user.userInfo.dashboard = '0'
        user.token = "SCUI.Administrator.Auth"
        sqlStr = "SELECT u.userId,u.userName,u.name,u.orgId,o.parentId,orgName,getParentList(u.orgId) as fullorgName from sys_user u left join sys_organization o on u.orgId=o.orgId \
                    where u.userName = '"+ req.body.username + "'"
        rows = await mysqlHelper.query(sqlStr)
        if(rows.length>0){
            user.userInfo.deptId=rows[0].orgId
            user.userInfo.deptName=rows[0].orgName
            user.userInfo.deptLongName=rows[0].fullorgName
            user.userInfo.deptTtype=rows[0].parentId==0?'中心':'台站'
        }

        sqlStr = "SELECT a.userName,b.alias FROM sys_user_role a INNER JOIN sys_role b on a.roleId=b.roleId \
                    where a.userId = (select userId from sys_user where userName='"+ req.body.username + "')"
        rows = await mysqlHelper.query(sqlStr)
        var roles = rows.map(v => v.alias)
        user.userInfo.role = roles

        result.code = 200
        result.data = user
        result.success = true
    } catch (err) {
        result.code = 400
        result.success = false
        result.message = err.message
    }
    res.json(result)
})


module.exports = router
